package com.mingqijia.gassafety.job.job.equipment;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.gap.cache.redis.RedisCache;
import com.mingqijia.gassafety.db.entity.Consumer;
import com.mingqijia.gassafety.db.entity.Dtu;
import com.mingqijia.gassafety.db.entity.DtuAep;
import com.mingqijia.gassafety.db.influxdb.config.InfluxDBConfiguration;
import com.mingqijia.gassafety.db.mapper.ConsumerMapper;
import com.mingqijia.gassafety.db.mapper.DtuAepMapper;
import com.mingqijia.gassafety.db.mapper.DtuMapper;
import com.mingqijia.gassafety.shared.constant.Constants;
import com.mingqijia.gassafety.shared.constant.EquipmentType;
import com.mingqijia.gassafety.shared.utils.RedisCacheExt;
import lombok.extern.slf4j.Slf4j;
import org.checkerframework.checker.units.qual.C;
import org.influxdb.dto.QueryResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;

import java.util.*;

/**
 * @author zhangfei
 * @version 1.0.0
 * @ClassName EquipmentSynchrodataJob.java
 * @Description 设备数据同步
 * @createTime 2022年03月02日
 */
@Configuration
@EnableScheduling
@Slf4j
public class EquipmentSynchrodataJob {

    @Autowired
    InfluxDBConfiguration influxDBConnect;
    @Autowired
    RedisCache redisCache;
    @Autowired
    RedisCacheExt redisUtil;
    @Autowired
    DtuMapper dtuMapper;

    @Autowired
    DtuAepMapper dtuAepMapper;
    @Autowired
    ConsumerMapper consumerMapper;

    /**
     * 设备数据同步，五分钟一次    0 0/5 * * * ?
     */
//    @Scheduled(cron = "${gassafety.warnStrategy.job.equipmentSynchrodata}")
//    public void equipmentSynchrodata() {
//        log.info("EquipmentSynchrodataJob--start--------");
//        //防重复锁
//        String key = Constants.ADD_EQUIPMENT;
//        try {
//            Boolean acquire = redisUtil.setIfAbsent(key, String.valueOf(System.currentTimeMillis()), Constants.TIME_OUT);//15分钟超时
//            if (acquire) {
//                List<Dtu> data = new ArrayList<>();
//                List<Dtu> dtus = dtuMapper.selectEquipment(EquipmentType.GAS_ALARM_CONTROLLER.getCode());
//                log.info("equipmentSynchrodata-需要处理的数据：{}", JSONObject.toJSONString(dtus));
//
//               List<Map<String,Object>> points = new ArrayList<>();
//                for (Dtu dtu : dtus) {
//                    String imei = dtu.getIMEI();
//                    Map<String, JSONObject> map = redisCache.getCacheMap("department_" + dtu.getPath());
//                    log.info("equipmentSynchrodata-获取到缓存数据map：{}", JSONObject.toJSONString(map));
//                    if (map == null || map.size() <= 0) continue;
//                    JSONObject latestDetector = map.get(imei);
//                    if (latestDetector == null) {
//                        dtuMapper.deleteByImei(imei + "-");
//                    }
//                    if (latestDetector != null && latestDetector.getInteger("type") == 5) {
//                        Map<String, Object> s = new HashMap<>();
//                        s.put("imei",imei);
//                        s.put("consumerId",dtu.getConsumerId());
//                        points.add(s);
//                        JSONArray detectorMeasures = latestDetector.getJSONArray("detectorMeasures");
//                        detectorMeasures.forEach(o -> {
//                            JSONObject jsonObject = JSONObject.parseObject(o + "");
//                            Dtu d = new Dtu();
//                            String subId = jsonObject.getString("subId");
//                            d.setId(imei + "-" + subId);
//                            d.setIMEI(imei + "-" + subId);
//                            d.setPath(dtu.getPath());
//                            d.setConsumerId(dtu.getConsumerId());
//                            d.setEquipmentType(EquipmentType.POINT_TYPE_GAS_DETECTOR.getCode());
//                            d.setValidity(dtu.getValidity());
//                            d.setEquipmentModel(dtu.getEquipmentModel());
//                            d.setExpirationTime(dtu.getExpirationTime());
//                            //获取这个点位
//                            QueryResult query = influxDBConnect
//                                    .getInfluxDBConnect()
//                                    .query("select * from DataLogAsDetector  where  DtuId= " + "'" + imei + "'" + " ORDER BY time ASC limit 1");
//                            List<QueryResult.Series> series = query.getResults().get(0).getSeries();
//                            if (series != null) {
//                                Object o1 = series.get(0).getValues().get(0).get(0);
//                                DateTime parse = DateUtil.parse(o1 + "");
//                                String format = DateUtil.format(parse, "yyyy-MM-dd HH:mm:ss");
//                                d.setNetInTime(format);
//                                d.setRegisterTime(format);
//                            }
//                            d.setInstallTime(new Date());
//                            d.setDeviceCode(dtu.getDeviceCode() + "-" + subId);
//                            d.setSpId(dtu.getSpId());
//                            d.setEquipmentManufacturer(dtu.getEquipmentManufacturer());
//                            d.setDetectionType(dtu.getDetectionType());
//                            d.setIsDeleted(0);
//                            data.add(d);
//                        });
//                    }
//                }
//                if (!CollectionUtil.isEmpty(data)) {
//                    dtuMapper.deleteByImeis(data);
//                }
//                log.info("EquipmentSynchrodataJob--本次同步数据：{}", JSONObject.toJSONString(data));
//                List<Dtu> inserts = new ArrayList<>();
//                List<Dtu> updates = new ArrayList<>();
//                if (!CollectionUtil.isEmpty(data)) {
//                    // 区分更新和新增数据
//                    List<String> imeis = dtuMapper.selectImei();
//                    if (!CollectionUtil.isEmpty(imeis)) {
//                        for (Dtu dtu : data) {
//                            dtu.setCmpRegistered(1);
//                            if (!imeis.contains(dtu.getIMEI())) {
//                                inserts.add(dtu);
//                            } else {
//                                updates.add(dtu);
//                            }
//                        }
//                    } else {
//                        inserts = data;
//                    }
//                    if (!CollectionUtil.isEmpty(inserts)) {
//                        dtuMapper.insertBatch(inserts);
//                    }
//                    if (!CollectionUtil.isEmpty(updates)) {
//                        updates.forEach(dtu -> {
//                            UpdateWrapper<Dtu> wrapper = new UpdateWrapper<>();
//                            wrapper.or().lambda()
//                                    .eq(Dtu::getIMEI, dtu.getIMEI());
//                            dtuMapper.update(dtu, wrapper);
//                        });
//
//                    }
//                    if (!CollectionUtil.isEmpty(points)) {
//                        points.forEach(stringObjectMap -> {
//                            Consumer consumer = consumerMapper.selectById(stringObjectMap.get("consumerId")+"");
//                            if (consumer!=null&&consumer.getId()!=null){
////                                Integer pointTotal = consumer.getPointTotal();
//                               Integer count= dtuMapper.selectCountByImei(stringObjectMap.get("imei")+"");
//                                consumer.setPointTotal(count);
//                                consumerMapper.updateById(consumer);
//                            }
//                        });
//                    }
//                    log.info("equipmentSynchrodata-本次新增数据：{}", JSONObject.toJSONString(inserts));
//                    log.info("equipmentSynchrodata-本次更新数据：{}", JSONObject.toJSONString(updates));
//                }
//                log.info("EquipmentSynchrodataJob--end--------");
//            }
//        } catch (Exception e) {
//            log.info("equipmentSynchrodata-error:{}", e);
//        } finally {
//            redisUtil.del(key);
//        }
//    }


    /**
     * 设备首次上报时间同步    0 0/5 * * * ?
     */
    // @Scheduled(cron = "${gassafety.warnStrategy.job.equipmentSynchrodata}")
    public void updateEquipmentNetInTime() {

        log.info("updateEquipmentNetInTime--start--------");
        //防重复锁
        String key = Constants.UPDATE_EQUIPMENT;
        try {
            Boolean acquire = redisUtil.setIfAbsent(key, String.valueOf(System.currentTimeMillis()), Constants.TIME_OUT);//15分钟超时
            if (acquire) {
                try {
                    List<Dtu> dtus = dtuMapper.selectNetInTimes();
                    log.info("updateEquipmentNetInTime-本次要处理的数据：{}", JSONObject.toJSONString(dtus));
                    if (!CollectionUtil.isEmpty(dtus)) {
                        for (Dtu dtu : dtus) {
                            String imei = dtu.getIMEI();
                            QueryResult query = influxDBConnect.getInfluxDBConnect()
                                    .query("select * from DataLogAsDetector  where  DtuId= " + "'" + imei + "'" + " ORDER BY time ASC limit 1");
                            if (query.getResults() != null && !CollectionUtil.isEmpty(query.getResults())
                                    && query.getResults().get(0).getSeries() != null) {
                                Object o = query.getResults().get(0).getSeries().get(0).getValues().get(0).get(0);
                                DateTime parse = DateUtil.parse(o + "");
                                String formatDate = DateUtil.format(parse, "yyyy-MM-dd HH:mm:ss");
                                dtu.setNetInTime(formatDate);
                                UpdateWrapper<Dtu> wrapper = new UpdateWrapper<>();
                                wrapper.lambda().or().eq(Dtu::getIsDeleted, 0)
                                        .eq(Dtu::getIMEI, dtu.getIMEI())
                                        .eq(Dtu::getNetInTime, "");
                                dtuMapper.update(dtu, wrapper);
                                //更新aep关联表
    //                            DtuAep dtuAep = new DtuAep();
    //                            dtuAep.setIMEI(imei);
    //                            dtuAep.setActivateTime(formatDate);
    //                            UpdateWrapper<DtuAep> wrapperUpdate = new UpdateWrapper<>();
    //                            wrapperUpdate.lambda().eq(DtuAep::getIsDeleted,0)
    //                                    .eq(DtuAep::getIMEI,imei);
    //                            int update = dtuAepMapper.update(dtuAep, wrapperUpdate);
    //                            log.info("updateEquipmentNetInTime-更新：{}的激活时间:{}",imei, update);
                            }
                        }
                    }
                } catch (Exception e) {
                    log.error("updateEquipmentNetInTime-error:{}", e);
                }finally {
                    redisUtil.del(key);
                }
            }
        } catch (Exception e) {
            log.error("updateEquipmentNetInTime-error:{}", e);
        }
    }
}
